using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.IO;
using Rotempco.Core.Logging.Objects;
using Rotempco.Core.Logging.Objects.Exceptions;
using Rotempco.Core.Logging.Logic;
using Rotempco.Core.Logging.Objects.Stores;
using Rotempco.Core.Logging.EntityObjects.Objects;

namespace Rotempco.Core.Logging.Managers.LogProviders
{
    internal class LogToEmailManager
    {
        internal void SendLogMessage(LogStack logEntry)
        {
            if (LogSettingsStore.Instance.LogSettings == null
                || string.IsNullOrEmpty(LogSettingsStore.Instance.LogSettings.RelayHost) 
                || string.IsNullOrEmpty(LogSettingsStore.Instance.LogSettings.SenderAddress)
                || LogSettingsStore.Instance.LogSettings.RecipientList.Length == 0 )
                throw new LogConfigurationException("Log not configured for Email");

            string senderName = logEntry.SourceMachineName;
            string subject = "Log from server: " + logEntry.SourceMachineName;
            
            MailPriority prirority = MailPriority.Normal;
            AlternateView plainBody = AlternateView.CreateAlternateViewFromString(LogStackConverter.ToPlainString(logEntry), null, "text/plain");
            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(GetHTMLBody(logEntry, subject), null, "text/html");

            foreach (string recipient in LogSettingsStore.Instance.LogSettings.RecipientList)
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(LogSettingsStore.Instance.LogSettings.SenderAddress, senderName);
                mail.To.Add(recipient);
                mail.IsBodyHtml = true;
                mail.Subject = subject;
                mail.Priority = prirority;
                mail.AlternateViews.Add(plainBody);
                mail.AlternateViews.Add(htmlBody);

                SmtpClient smtp = new SmtpClient();
                smtp.Host = LogSettingsStore.Instance.LogSettings.RelayHost;

               smtp.Send(mail);
            }
        }

        private static string GetHTMLBody(LogStack logEntry, string subject)
        {
            string htmlBody = LogStackConverter.ToHTMLString(logEntry);
            return htmlBody;
        }
    }
}
